//插件加载
import plugin from '../../../lib/plugins/plugin.js'
import data from '../model/XiuxianData.js'
import config from "../model/Config.js"
import { existplayer, Write_player, Write_equipment } from './xiuxian.js'
import { Read_player, Read_equipment } from './xiuxian.js'
import { Add_HP,Add_修为 } from './xiuxian.js'
/**
 * 全局变量
 */
/**
 * 境界模块
 */
export class Level extends plugin {
    constructor() {
        super({
            name: 'Yunzai_Bot_Level',
            dsc: '修仙模块',
            event: 'message',
            priority: 600,
            rule: [
                {
                    reg: '^#突破$',
                    fnc: 'Level_up'
                },
                {
                    reg: '^#渡劫$',
                    fnc: 'fate_up'
                },
                {
                    reg: '^#服用$',
                    fnc: 'Useitems'
                },
                {
                    reg: '^#羽化登仙$',
                    fnc: 'Level_up_Max'
                },
            ]
        })
        this.xiuxianConfigData = config.getConfig("xiuxian", "xiuxian");
    }



    //突破
    async Level_up(e) {
        let usr_qq = e.user_id;
        //有无账号
        let ifexistplay = await existplayer(usr_qq);

        if (!ifexistplay) {
            return;
        }

        //不开放私聊
        if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }

        //获取游戏状态
        let game_action = await redis.get("xiuxian:player:" + usr_qq + ":game_action");

        //防止继续其他娱乐行为
        if (game_action == 0) {
            e.reply("修仙：游戏进行中...");
            return;
        }


        //读取信息
        let player = await Read_player(usr_qq);
        //境界
        let now_level = player.境界;
        if (now_level == "渡劫期") {
            //检查仙门是否开启！
            let power_place = await redis.get("xiuxian:player:" + usr_qq + ":power_place");
            if (power_place == 0) {
                e.reply("你已度过雷劫，请感应仙门#羽化登仙");
            }
            else {
                e.reply(`请先渡劫！`);
            }
            return;
        }

        //修为
        let now_exp = player.修为;

        //需要的修为
        let need_exp = data.Level_list.find(item => item.level == now_level).exp;

        //根据名字取找境界id
        let now_level_id = data.Level_list.find(item => item.level == now_level).level_id;
        if (now_level_id == 46) {
            e.reply(`您已是此界凡人`);
            return;
        }

        if (now_exp < need_exp) {
            e.reply(`修为不足,再积累${need_exp - now_exp}修为后方可突破`);
            return;
        }

        
        var Time=this.xiuxianConfigData.CD.level_up;
        let now_Time = new Date().getTime(); //获取当前时间戳
        let shuangxiuTimeout = parseInt(60000 * Time);
        let last_time = await redis.get("xiuxian:player:" + usr_qq + ":last_Levelup_time");//获得上次的时间戳,
        last_time = parseInt(last_time);
        if (now_Time < last_time + shuangxiuTimeout) {
            let Couple_m = Math.trunc((last_time + shuangxiuTimeout - now_Time) / 60 / 1000);
            let Couple_s = Math.trunc(((last_time + shuangxiuTimeout - now_Time) % 60000) / 1000);
            e.reply("突破正在CD中，" + `剩余cd:  ${Couple_m}分 ${Couple_s}秒`);
            return;
        }


        //随机数
        let rand = Math.random();
        let prob = 1 - (now_level_id - 1) / 50;
        //突破失败了！
        if (rand > prob) {
            let bad_time = Math.random();//增加多种突破失败情况，顺滑突破丢失修为曲线
            if (bad_time > 0.9) {
                await Add_修为(usr_qq, -1 * need_exp * 0.4);
                await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
                e.reply(`突然听到一声鸡叫,鸡..鸡..鸡...鸡你太美！！！是翠翎恐蕈，此地不适合突破，快跑！险些走火入魔，丧失了` + (need_exp) * 0.4 + "修为");
                return;
            }
            else if (bad_time > 0.8) {
                await Add_修为(usr_qq, -1 * need_exp * 0.2);
                await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
                e.reply(`突破瓶颈时想到树脂满了,险些走火入魔，丧失了` + (need_exp) * 0.2 + "修为");
                return;
            }
            else if (bad_time > 0.7) {
                await Add_修为(usr_qq, -1 * need_exp * 0.1);
                await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
                e.reply(`突破瓶颈时想起背后是药园，刚种下掣电树种子，不能被破坏了，打断突破，嘴角流血，丧失了` + (need_exp) * 0.1 + "修为");
                return;
            }
            else if (bad_time > 0.1) {
                await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
                e.reply(`憋红了脸，境界突破失败,等到${Time}分钟后再尝试吧`);
                return;
            }
            else {
                await Add_修为(usr_qq, -1 * need_exp * 0.2);
                await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
                e.reply(`突破瓶颈时想起怡红院里的放肆,想起了金银坊里的狂热,险些走火入魔，丧失了` + (need_exp) * 0.2 + "修为");
                return;
            }
        }
        //境界提升,修为扣除,攻防血重新加载,当前血量拉满
        player.境界 = data.Level_list.find(item => item.level_id == now_level_id + 1).level;
        player.修为 -= need_exp;
        player.基础血量 = data.Level_list.find(item => item.level == player.境界).基础血量;
        player.基础防御 = data.Level_list.find(item => item.level == player.境界).基础防御;
        player.基础攻击 = data.Level_list.find(item => item.level == player.境界).基础攻击;
        player.基础暴击 = data.Level_list.find(item => item.level == player.境界).基础暴击;
        await Write_player(usr_qq, player);
        let equipment = await Read_equipment(usr_qq);
        await Write_equipment(usr_qq, equipment);
        await Add_HP(usr_qq, 99999999);
        e.reply(`突破成功,当前境界为${player.境界}`);
        await redis.set("xiuxian:player:" + usr_qq + ":last_Levelup_time",now_Time);//获得上次的时间戳
        return;
    }



    //渡劫
    async fate_up(e) {
        let usr_qq = e.user_id;
        //有无账号
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }


        //不开放私聊
        if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }


        //获取游戏状态
        let game_action = await redis.get("xiuxian:player:" + usr_qq + ":game_action");
        //防止继续其他娱乐行为
        if (game_action == 0) {
            e.reply("修仙：游戏进行中...");
            return;
        }

        //读取信息
        let player = await Read_player(usr_qq);

        //境界
        let now_level = player.境界;


        if (now_level != "渡劫期") {
            e.reply(`你非渡劫期修士！`);
            return;
        }


        //查询redis中的人物动作
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        //不为空
        if (action != null) {
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }

        //检查仙门是否开启！
        let power_place = await redis.get("xiuxian:player:" + usr_qq + ":power_place");


        if (power_place == 0) {
            //已经开了
            e.reply("你已度过雷劫，请感应仙门#羽化登仙");
            return;
        }


        //看看当前血量
        let now_HP = player.当前血量;
        //查看境界血量-----不是根据血量上限
        let list_HP = data.Level_list.find(item => item.level == now_level).基础血量;
        if (now_HP < list_HP * 0.9) {
            e.reply(player.名号 + "血量亏损，强行渡劫后晕倒在地！");
            return;
        }

        //修为
        let now_exp = player.修为;
        //需要的修为
        let need_exp = data.Level_list.find(item => item.level == now_level).exp;
        //境界id
        let now_level_id = data.Level_list.find(item => item.level == now_level).level_id;
        if (now_level_id == 46) {
            e.reply(`您已是此界凡人`);
            return;
        }

        if (now_exp < need_exp) {
            e.reply(`修为不足,再积累${need_exp - now_exp}修为后方可突破`);
            return;
        }


        //////////////////////////////////////////////计算当前面板  ---十万级
        var new_blood = player.血量上限;
        var new_defense = player.防御;
        var new_attack = player.攻击;
        //渡劫期基础血量为1600000。防御800000，攻击800000 
        new_blood = new_blood / 100000;
        new_defense = new_defense / 100000;
        new_attack = new_attack / 100000;
        //取值比例4.6.2
        new_blood = (new_blood * 4) / 10;
        new_defense = (new_defense * 6) / 10;
        new_attack = (new_attack * 2) / 10;
        //基础厚度
        var N = new_blood + new_defense;
        //你的系数
        var x = N * new_attack;
        //系数只取到后两位
        x = x.toFixed(2);
        ///////////////////////////////////////////


        //渡劫系数区间
        var n = 18;//最低
        var p = 5;//变动
        var m = n + 5;

        if (x <= n) {
            //没有达到最低要求
            player.当前血量 = 0;
            player.修为 -= parseInt(need_exp / 4);
            await Write_player(usr_qq, player);
            e.reply("天空一声巨响，未降下雷劫，就被天道的气势震死了。");
            return;
        }



        var y = 1;

        if(player.灵根.type=="伪灵根"){
            y=3;
        }
        else if(player.灵根.type=="真灵根"){
            x=x*1+0.5;
            y=6;
        }
        else if(player.灵根.type=="天灵根"){
            x=x*1+0.75;
            y=9;
        }
        else{
            x=x*1+1;
            y=12;
        }
        
        //渡劫成功率
        var l = (x - n) / p;
        l = l * 100;
        l = l.toFixed(2);

        e.reply("天道：就你，也敢逆天改命？");
        e.reply("["+player.名号+"]"+"\n雷抗："+ x+"\n成功率：" + l + "%\n灵根："+player.灵根.type+"\n需渡"+y+"道雷劫\n将在一分钟后落下\n请做好准备！\n若有其他修仙者渡劫雷劫将会抢走\n请把其他渡劫期打死后再渡劫！");

        //在redis中添加状态
        var time = 60;//时间(分)九个雷，//60分钟。防延迟。
        let action_time = 60000 * time;//持续时间，单位毫秒

        let arr = {
            "action": "渡劫",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "time": action_time,//持续时间
            "shutup":"1",//闭关状态-关闭
            "working":"1",//劳动状态-关闭
            "Place_action": "1",//秘境状态---关闭
            "Place_actionplus": "1",//沉迷---关闭
            "power_up": "0",//渡劫状态--开启
            ///以下都不是基础字段
            "power_distortion": x,//畸变系数，此函数独有
            "power_Grade": y,//雷等级，也就是最多次数限制
            "power_n": n,//雷畸变最小区间
            "power_m": m,//雷畸变最大区间
        };

        //消息设置
        if (e.isGroup) {
            arr.group_id = e.group_id
        }

        //此人需要渡劫，确保未开
        redis.set("xiuxian:player:" + usr_qq + ":power_place", 1);
        
        //初始化雷数
        redis.set("xiuxian:player:" + usr_qq + ":power_aconut", 1);

        //redis设置动作
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));

        return;
    }



    //#羽化登仙
    //专门为渡劫期设计的指令
    async Level_up_Max(e) {
        let usr_qq = e.user_id;

        //有无账号
        let ifexistplay = await existplayer(usr_qq);

        if (!ifexistplay) {
            return;
        }

        //不开放私聊
        if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }


        //获取游戏状态
        let game_action = await redis.get("xiuxian:player:" + usr_qq + ":game_action");
        //防止继续其他娱乐行为
        if (game_action == 0) {
            e.reply("修仙：游戏进行中...");
            return;
        }

        //读取信息
        let player = await Read_player(usr_qq);

        //境界
        let now_level = player.境界;



        if (now_level != "渡劫期") {
            e.reply(`你非渡劫期修士！`);
            return;
        }


        //查询redis中的人物动作
        let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
        action = JSON.parse(action);
        //不为空
        if (action != null) {
            let action_end_time = action.end_time;
            let now_time = new Date().getTime();
            if (now_time <= action_end_time) {
                let m = parseInt((action_end_time - now_time) / 1000 / 60);
                let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
                e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
                return;
            }
        }

        //检查仙门是否开启！
        let power_place = await redis.get("xiuxian:player:" + usr_qq + ":power_place");

        if (power_place == 1) {
            e.reply("请先渡劫！");
            return;
        }

        //需要的修为
        let need_exp = data.Level_list.find(item => item.level == now_level).exp;

        //根据名字取找境界id
        let now_level_id = data.Level_list.find(item => item.level == now_level).level_id;

        if (power_place == 0) {
            e.reply("天空一声巨响，一道虚影从眼中浮现，突然身体微微颤抖，似乎感受到了什么，" + player.名号 + "来不及思索，立即向前飞去！只见万物仰头相望，似乎感觉到了，也似乎没有感觉，殊不知......");
            //境界提升,修为扣除,攻防血重新加载,当前血量拉满
            player.境界 = data.Level_list.find(item => item.level_id == now_level_id + 1).level;
            player.修为 -= need_exp;
            player.基础血量 = data.Level_list.find(item => item.level == player.境界).基础血量;
            player.基础防御 = data.Level_list.find(item => item.level == player.境界).基础防御;
            player.基础攻击 = data.Level_list.find(item => item.level == player.境界).基础攻击;
            player.基础暴击 = data.Level_list.find(item => item.level == player.境界).基础暴击;
            await Write_player(usr_qq, player);
            let equipment = await Read_equipment(usr_qq);
            await Write_equipment(usr_qq, equipment);
            await Add_HP(usr_qq, 99999999);
            return;
        }
        return;
    }
}